package com.pruebas.entity;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.FetchType;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.TypedQuery;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.hibernate.annotations.Type;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.tostring.RooToString;

@RooJavaBean
@RooToString
@RooJpaActiveRecord
public class ExamModel {

    @ManyToMany(cascade = CascadeType.ALL)
    private Set<QuestionModel> questionList = new HashSet<QuestionModel>();

    @NotNull
    @Column(unique = true)
    private String examNumber;

    @NotNull
    @Size(max = 2000)
    private String examDescription;

    @NotNull
    @ManyToOne(fetch = FetchType.EAGER)
    private Profile profile;
    
    @ManyToOne(fetch = FetchType.EAGER)
    private User user;
    
    @NotNull
    @Type(type="yes_no")
    private Boolean sharedExam;
    
    public static List<ExamModel> findExamModelList(int firstResult, int maxResults,Long userId){
        StringBuffer queryString = new StringBuffer();
        //StringBuffer queryString2 = new StringBuffer();
        
        queryString.append("SELECT o FROM ExamModel o,User u");
        queryString.append(" Where (o.sharedExam='y' or ( o.user.id=:userId and o.sharedExam='n'))");
        queryString.append(" and o.user.id=u.id");
        
        /*
        queryString2.append("SELECT o FROM ExamModel o,User u");
        queryString2.append(" Where o.user.id=:userId");
        queryString2.append(" and o.user.id=u.id");
         */
        
        
        TypedQuery<ExamModel> query = ExamModel.entityManager().createQuery(queryString.toString(), ExamModel.class);
        //TypedQuery<ExamModel> query = ExamModel.entityManager().createQuery(queryString2.toString(), ExamModel.class);
        query.setFirstResult(firstResult);
        query.setMaxResults(maxResults);
        query.setParameter("userId", userId);
        
        List l =  query.getResultList();
        return l;
        
    }    
    
}
